﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Transactions;
using TRL.DataAccessLayer;

namespace TRL.TRLAdmin.UserMgmt
{
    public partial class DeleteUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Guid userIdToDelete;
            // If the userId querystring parameter is not specified or we can not parse it into a GUID, return
            // an error to the user.
            if ((Request.QueryString["userId"] == null) || !(Guid.TryParse(Request.QueryString["userId"].ToString(), out userIdToDelete)))
            {
                displayMessage(MessageType.Error, "The userId of the user to remove is not specified or is in a invalid form.");
            }
            else
            {
                // Querystring userIdToDelete is a valid GUID. Try to delete user.
                try
                {
                    //using (var ts = new TransactionScope())
                    //{
                        var membership = Membership.GetUser(userIdToDelete);
                        var dc = new DataClasses1DataContext();
                        var userInfo =
                            (from u in dc.AdminUserInfos
                             where u.userId == userIdToDelete
                             select u).First();
                        dc.AdminUserInfos.DeleteOnSubmit(userInfo);
                        dc.SubmitChanges();

                        Membership.DeleteUser(membership.UserName);

                    //    ts.Complete();
                    //}
                    Response.Redirect("viewUsers.aspx", true);
                }
                catch (Exception ex)
                {
                    displayMessage(MessageType.Error, "Error deleting user. Error: " + ex.Message);           
                }
            }
        }

        private enum MessageType { Success, Error }

        /// <summary>
        /// Displays an error message to the user.
        /// </summary>
        /// <param name="msg"></param>
        private void displayMessage(MessageType type, string msg)
        {
            if (type == MessageType.Error)
                message.CssClass = "alert alert-error";
            else
                message.CssClass = "alert alert-success";

            message.Visible = true;
            message.Text = msg;
        }

    }
}